package org.jeecg.modules.wlhy.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.*;
import org.jeecg.modules.middleware.rabbitmq.gen.EnumGenHandler;
import org.jeecg.modules.middleware.rabbitmq.gen.GenMqUtil;
import org.jeecg.modules.third.amap.dto.MapDirectionDTO;
import org.jeecg.modules.third.amap.service.AmapService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.customer.entity.*;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAddressReceiveService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAddressSendService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerConfigService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hycustomeragent.entity.HyCustomerAgent;
import org.jeecg.modules.wlhy.hycustomeragent.service.IHyCustomerAgentService;
import org.jeecg.modules.wlhy.hyzyb.service.IHyZybService;
import org.jeecg.modules.wlhy.order.entity.*;
import org.jeecg.modules.wlhy.order.mapper.HyOrderMapper;
import org.jeecg.modules.wlhy.order.service.IHyOrderReceiveAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderSendAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.order.vo.HyOrderVO;
import org.jeecg.modules.wlhy.shipping.constant.ShippingStatus;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: hy_order
 * @Author: jeecg-boot
 * @Date: 2020-12-03货源管理
 * @Version: V1.0
 */
@Service
@Slf4j
public class HyOrderServiceImpl extends ServiceImpl<HyOrderMapper, HyOrder> implements IHyOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HyOrderServiceImpl.class);

    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    private IHyShippingNoteService hyShippingNoteService;
    @Autowired
    private IHyCustomerService hyCustomerService;
    @Autowired
    private IHyOrderSendAddressService hyOrderSendAddressService;
    @Autowired
    private IHyOrderReceiveAddressService hyOrderReceiveAddressService;

    @Autowired
    private IHyCustomerAddressReceiveService customerAddressReceiveService;

    @Autowired
    private IHyCustomerAddressSendService customerAddressSendService;

    @Autowired
    private IHyCustomerAgentService customerAgentService;

    @Autowired
    private IHyCustomerConfigService customerConfigService;

    @Autowired
    private IHyZybService zybService;

    @Autowired
    private AmapService amapService;

    @Autowired
    private IHyCompanyConfigService companyConfigService;

    @Autowired
    private RedisUtil redisUtil;



    @Override
    public int getCountByDate(String dateString) {
        return baseMapper.getCountByDate(dateString);
    }

    @Override
    public List<OrderMonthTotalDTO> getOrderMonthTotal(String customerId, String startMonth, String endMonth) {
        return baseMapper.getOrderMonthTotal(customerId, startMonth, endMonth);
    }

    @Override
    public IPage<HyOrderVO> getPageList(Page<HyOrderVO> page, QueryWrapper<HyOrderVO> queryWrapper) {
        IPage<HyOrderVO> pageList = baseMapper.getPageList(page, queryWrapper);
        return pageList;
    }

    @Override
    public IPage<HyOrderVO> getPageListByDis(Page<HyOrderVO> page, Map p) {
        return page.setRecords(baseMapper.getPageListByDis(page, p));
    }

    @Override
    public int getShippingNums(String orderId) {
        return hyShippingNoteService.count(new QueryWrapper<HyShippingNote>().eq("order_id", orderId));
    }

    @Override
    @Transactional
    public Result addOrder(HyOrderDTO hyOrder) {
        HyCustomer customer = null;
        //是否是货主
        if (userUtil.isSys()) {
            String customerId = hyOrder.getCustomerId();
            if (StringUtils.isEmpty(customerId)) {
                return Result.error("货主信息不存在");
            }
            customer = hyCustomerService.getById(customerId);
        } else {
            customer = userUtil.getCustomer();
        }
        if (customer == null) {
            return Result.error("货主信息不存在");
        }
        String customerId = customer.getId();

        String orderMode = hyOrder.getOrderMode();//货源模式
        if ("3".equals(orderMode)) {
            //货主发布差价货源
            BigDecimal agentPrice = hyOrder.getAgentPrice();//经纪人运费
            if (agentPrice == null) {
                return Result.error("经纪人运费不能为空");
            }
            //BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
//            if(shippingUnitPrice!=null) {
//                if (shippingUnitPrice.compareTo(agentPrice) == 1) {
//                    return Result.error("司机运费不能大于经纪人运费");
//                }
//            }
            //经纪人
            String agentId = hyOrder.getAgentId();
            if (StringUtils.isEmpty(agentId)) {
                return Result.error("经纪人不能为空");
            }
            if (StringUtils.equals(customerId, agentId)) {
                return Result.error("货主和经纪人不能相同");
            }
            HyCustomerAgent customerAgent = customerAgentService.getByCustomerAndAgentId(customerId, agentId);
            if (customerAgent == null) {
                return Result.error("经纪人信息错误");
            }
        } else {
            customerId = customer.getId();
            BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
            if (shippingUnitPrice == null) {
                return Result.error("运费单价不能为空");
            }
        }

        return addOrder(hyOrder, customerId);
    }

    @Override
    public Result<?> addAgentOrder(HyOrderDTO hyOrder) {
        BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
        if (shippingUnitPrice == null) {
            return Result.error("司机运费不能为空");
        }

        HyCustomer customer = userUtil.getCustomer();
        if (customer == null) {
            return Result.error("货主信息不存在");
        }
        String customerId = hyOrder.getCustomerId();
        if (StringUtils.isEmpty(customerId)) {
            return Result.error("货主不能为空");
        }

        String agentId = customer.getId();//经纪人
        //经纪人代发差价货源
        hyOrder.setOrderMode("3");
        hyOrder.setAgentId(agentId);//经纪人

        if (StringUtils.equals(customerId, agentId)) {
            return Result.error("货主和经纪人不能相同");
        }

        HyCustomerAgent customerAgent = customerAgentService.getByCustomerAndAgentId(customerId, agentId);
        if (customerAgent == null) {
            return Result.error("经纪人信息错误");
        }

        return addOrder(hyOrder, customerId);
    }

    private Result<?> addOrder(HyOrderDTO hyOrder, String customerId) {

        if ("2".equals(hyOrder.getOrderStatus())) {
            BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
            if (shippingUnitPrice == null) {
                return Result.error("运费单价不能为空");
            }
            hyOrder.setDtPublish(new Date());//货源发布日期
        }
        String orderType = hyOrder.getOrderType();
        if (StringUtils.isEmpty(orderType)) {
            return Result.error("货源类型不能为空");
        }
        if ("1".equals(orderType)) {

        } else if ("2".equals(orderType)) {
            String orderType2 = hyOrder.getOrderType2();
            if (!"1".equals(orderType2) && !"2".equals(orderType2)) {
                return Result.error("货源类型");
            }
            if (hyOrder.getVehicleNum() == null) {
                return Result.error("需求车辆数不能为空");
            }
        } else {
            return Result.error("货源类型错误");
        }
        if (StringUtils.isEmpty(hyOrder.getDescriptionOfGoods())) {
            return Result.error("货物名称不能为空");
        }
        if (StringUtils.isEmpty(hyOrder.getCargoTypeClassificationCode())) {
            return Result.error("货物分类不能为空");
        }

        String payType = hyOrder.getPayType();
        HyStatusCheckUtil.checkPayType(payType);
        if ("2".equals(payType)) {
            String carrierId = hyOrder.getCarrierId();
            if (StringUtils.isEmpty(carrierId)) {
                return Result.error("代收人不能为空!");
            }
            //0全部1按吨 2包车价
            String carrierFeeType = hyOrder.getCarrierFeeType();
            if ("1".equals(carrierFeeType)) {
                if (!"1".equals(hyOrder.getShippingType())) {
                    return Result.error("代收人运费计算方式必须是按单价");
                }
                BigDecimal carrierUnitFee = hyOrder.getCarrierUnitFee();
                if (carrierUnitFee == null || carrierUnitFee.compareTo(BigDecimal.ZERO) <= 0) {
                    return Result.error("代收人运费单价不能为0");
                }
                if (carrierUnitFee.compareTo(hyOrder.getShippingUnitPrice()) > 0) {
                    return Result.error("代收人运费单价不能大于运费单价");
                }
            }else if ("2".equals(carrierFeeType)) {
                BigDecimal carrierUnitFee = hyOrder.getCarrierUnitFee();
                if (carrierUnitFee == null || carrierUnitFee.compareTo(BigDecimal.ZERO) <= 0) {
                    return Result.error("代收人运费不能为0");
                }
            }else {
                hyOrder.setCarrierFeeType("0");
                hyOrder.setCarrierUnitFee(BigDecimal.ZERO);
            }
        } else {
            hyOrder.setCarrierFeeType("0");
            hyOrder.setCarrierUnitFee(BigDecimal.ZERO);
        }

        if ("3".equals(payType)) {
            String preType = hyOrder.getPreType();
            if (StringUtils.isEmpty(preType)) {
                return Result.error("预付运费计算方式不能为空!");
            }
            if (!"1".equals(preType) && !"2".equals(preType)) {
                return Result.error("预付运费计算方式错误");
            }
            BigDecimal preUnitFee = hyOrder.getPreUnitFee();
            if (preUnitFee == null) {
                return Result.error("预付运费不能为空");
            }
            if (!ConvertUtil.isMoney(preUnitFee.toString())) {
                return Result.error("预付运费错误");
            }
            //如果pay_type=3即预付类型需要对比预付金额和运费金额，预付金额必须小于运费金额
            if(NumberUtil.isGreaterOrEqual(hyOrder.getPreUnitFee(), hyOrder.getShippingUnitPrice()) ){
                return Result.error("预付金额必须小于运费金额");
            }

        }


        //处理收发货
        List<HyOrderSendAddress> sendAddressList = hyOrder.getHyOrderSendAddressList();
        if (sendAddressList == null) {
            return Result.error("未添加发货地址");
        }
        if (sendAddressList.size() == 0) {
            return Result.error("未添加发货地址");
        }
        int sendDestNums = 0;
        HyOrderSendAddress hyOrderSendAddressDest = null;
        for (HyOrderSendAddress item : sendAddressList) {
            if (StringUtils.isEmpty(item.getSendAddress())) {
                return Result.error("发货地址不能为空");
            }
            if (StringUtils.isEmpty(item.getSendContactName())) {
                return Result.error("发货联系人不能为空");
            }
            if (StringUtils.isEmpty(item.getSendContactTel())) {
                return Result.error("发货联系人电话不能为空");
            }
            if (StringUtils.isEmpty(item.getSendAreaCode())) {
                return Result.error("发货地省市区不能为空");
            }
           /* if (HyCfgUtil.getCfg("check_order_address")!=null){
                if(HyCfgUtil.isUsed("check_order_address")){
                    HyArea area = areaMapper.selectList(new LambdaQueryWrapper<HyArea>().eq(HyArea::getAreaCode, item.getSendAreaCode())).get(0);
                    if (area.getMergerName().contains("省")){
                        if (!item.getSendAddress().contains("省")||!item.getSendAddress().contains("市")||!item.getSendAddress().contains("区")||!item.getSendAddress().contains("县")){
                            return Result.error("发货详细地址缺失省市区三级名称");
                        }
                    }else if (area.getMergerName().contains("市")){
                        if (!item.getSendAddress().contains("市")||!item.getSendAddress().contains("区")||!item.getSendAddress().contains("县")){
                            return Result.error("发货详细地址缺失省市区三级名称");
                        }
                    }else {
                        if (!item.getSendAddress().contains("区")||!item.getSendAddress().contains("县")){
                            return Result.error("发货详细地址缺失省市区三级名称");
                        }
                    }
                }
            }*/


            BigDecimal lat = item.getSendLatitude();
            BigDecimal lng = item.getSendLongitude();
            if (lat == null || lng == null) {
                return Result.error("发货地址经纬度不能为空");
            }
            if (item.isIzDest()) {
                hyOrderSendAddressDest = item;
                sendDestNums++;
            }
        }
        if (sendDestNums == 0) {
            return Result.error("发货地址未添加始发地");
        }
        if (sendDestNums > 1) {
            return Result.error("发货地址不能有多个始发地");
        }
        hyOrder.setAddressSendId(hyOrderSendAddressDest.getAddressSendId());
        hyOrder.setSendDate(hyOrderSendAddressDest.getSendDate());
        hyOrder.setSendAddressName(hyOrderSendAddressDest.getSendAddressName());
        hyOrder.setSendLongitude(hyOrderSendAddressDest.getSendLongitude());
        hyOrder.setSendLatitude(hyOrderSendAddressDest.getSendLatitude());
        hyOrder.setSendAddress(hyOrderSendAddressDest.getSendAddress());
        hyOrder.setSendAreaCode(hyOrderSendAddressDest.getSendAreaCode().substring(0,6));
        hyOrder.setSendContactName(hyOrderSendAddressDest.getSendContactName());
        hyOrder.setSendContactTel(hyOrderSendAddressDest.getSendContactTel());
        hyOrder.setSendContactCredit(hyOrderSendAddressDest.getSendContactCredit());
        //收货地址
        List<HyOrderReceiveAddress> receiveAddressList = hyOrder.getHyOrderReceiveAddressList();
        if (receiveAddressList == null) {
            return Result.error("未添加收货地址");
        }
        if (receiveAddressList.size() == 0) {
            return Result.error("未添加收货地址");
        }
        int receiveDestNums = 0;
        HyOrderReceiveAddress hyOrderReceiveAddressDest = null;
        for (HyOrderReceiveAddress item : receiveAddressList) {
            if (StringUtils.isEmpty(item.getReceiveAddress())) {
                return Result.error("收货地址不能为空");
            }
            if (StringUtils.isEmpty(item.getReceiveContactName())) {
                return Result.error("收货联系人不能为空");
            }
            if (StringUtils.isEmpty(item.getReceiveContactTel())) {
                return Result.error("收货联系人电话不能为空");
            }
            if (StringUtils.isEmpty(item.getReceiveAreaCode())) {
                return Result.error("收货地省市区不能为空");
            }


           /* if (HyCfgUtil.getCfg("check_order_address")!=null){
                if(HyCfgUtil.isUsed("check_order_address")){
                    HyArea area = areaMapper.selectList(new LambdaQueryWrapper<HyArea>().eq(HyArea::getAreaCode, item.getReceiveAreaCode())).get(0);
                    if (area.getMergerName().contains("省")){
                        if (!item.getReceiveAddress().contains("省")||!item.getReceiveAddress().contains("市")||!item.getReceiveAddress().contains("区")||!item.getReceiveAddress().contains("县")){
                            return Result.error("发货详细地址缺失省市区三级名称");
                        }
                    }else {
                        if (!item.getReceiveAddress().contains("市")||!item.getReceiveAddress().contains("区")||!item.getReceiveAddress().contains("县")){
                            return Result.error("发货详细地址缺失省市区三级名称");
                        }
                    }
                }
            }*/


            BigDecimal lat = item.getReceiveLatitude();
            BigDecimal lng = item.getReceiveLongitude();
            if (lat == null || lng == null) {
                return Result.error("收货地址经纬度不能为空");
            }
            if (item.isIzDest()) {
                hyOrderReceiveAddressDest = item;
                receiveDestNums++;
            }
        }
        if (receiveDestNums == 0) {
            return Result.error("收货地址未添加目的地");
        }
        if (receiveDestNums > 1) {
            return Result.error("收货地址不能有多个目的地");
        }

        hyOrder.setAddressReceiveId(hyOrderReceiveAddressDest.getAddressReceiveId());
        hyOrder.setReceiveDate(hyOrderReceiveAddressDest.getReceiveDate());
        hyOrder.setReceiveAddressName(hyOrderReceiveAddressDest.getReceiveAddressName());
        hyOrder.setReceiveLongitude(hyOrderReceiveAddressDest.getReceiveLongitude());
        hyOrder.setReceiveLatitude(hyOrderReceiveAddressDest.getReceiveLatitude());
        hyOrder.setReceiveAddress(hyOrderReceiveAddressDest.getReceiveAddress());
        hyOrder.setReceiveAreaCode(hyOrderReceiveAddressDest.getReceiveAreaCode().substring(0,6));
        hyOrder.setReceiveContactName(hyOrderReceiveAddressDest.getReceiveContactName());
        hyOrder.setReceiveContactTel(hyOrderReceiveAddressDest.getReceiveContactTel());
        hyOrder.setReceiveContactCredit(hyOrderReceiveAddressDest.getReceiveContactCredit());

        //众汇要求货源部分添加里程数
        try {
            MapDirectionDTO mapDirectionDTO = this.amapService.getEstimateMileageForOrder(hyOrder);
            if (ObjectUtil.isNotEmpty(mapDirectionDTO)) {
                hyOrder.setMileage(new BigDecimal(mapDirectionDTO.getDistance()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        HyCustomerCompany customerCompany = userUtil.getCustomerCompany(customerId);
        BigDecimal costServicePercent = customerCompany.getCostServicePercent();
        if (costServicePercent == null) {
            return Result.error("服务费信息错误");
        }

        //鄂尔多斯市监管判断收发货必须有一个地点在内蒙古范围内
        if (HyCfgUtil.isUsed2("ordos_report")) {
            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(customerCompany.getCompanyId());
            //200是鄂尔多斯市监管平台，写死的
            if (hyCompanyConfig.getParkReportPlatformType().intValue() == 200) {
                if (!hyOrder.getSendAddress().contains("内蒙古") && !hyOrder.getReceiveAddress().contains("内蒙古")) {
                    return Result.error("发货或收货地址必须有一个在内蒙古自治区范围内");
                }
            }

            HyCustomer hyCustomer = this.hyCustomerService.getById(customerId);
            if (!"1".equals(hyCustomer.getTosUploadStatus())) {
                return Result.error("请先上报货主信息到鄂尔多斯市监管平台!");
            }
        }

        String shippingType = hyOrder.getShippingType();
        HyStatusCheckUtil.checkShippingType(shippingType);

        //验证油气费
        String izUsedGas = hyOrder.getIzUsedGas();
        if ("0".equals(izUsedGas)) {
            hyOrder.setGasRechargeAmount(BigDecimal.ZERO);
        } else {
            BigDecimal gasRechargeAmount = hyOrder.getGasRechargeAmount();
            if (gasRechargeAmount == null) {
                return Result.error("油气充值金额不正确");
            }
//            HyCompanyConfig companyConfig = hyCompanyConfigService.getByCompanyId(customerCompany.getCompanyId());
//            if(companyConfig == null){
//                return Result.error("未找到公司配置信息!");
//            }
//            if(!companyConfig.getIzGasUsed()){
//                return Result.error("签约公司不支持油气!");
//            }
            if ("1".equals(izUsedGas)) {
                //万金油
                HyConfig gasConfig = HyConfigUtils.getConfig();
                if (gasConfig == null) {
                    return Result.error("未找到万金油配置信息!");
                }
                if (!gasConfig.getGasIzUse()) {
                    return Result.error("万金油功能已关闭!");
                }
            }
//            if("2".equals(izUsedGas)){
//                //油气卡
//            }

            if ("3".equals(izUsedGas)) {
                //油气平台
                HyConfig gasConfig = HyConfigUtils.getConfig();
                if (gasConfig == null) {
                    return Result.error("未找到油气平台配置信息!");
                }
                if (!gasConfig.getHgGasIzUse()) {
                    return Result.error("油气平台功能已关闭!");
                }
            }
        }
        //验证货源单价风控
        Result<?> result = checkingFreight(hyOrder);
        if (result.getCode() == 500) {
            return result;
        }

        hyOrder.setCustomerId(customerId);
        //生成货源号
        String orderNum = codeUtil.createOrderNum();
        hyOrder.setOrderNum(orderNum);

        HyOrder hyOrderNew = new HyOrder();
        BeanUtils.copyProperties(hyOrder, hyOrderNew);
        this.save(hyOrderNew);
        if (redisUtil.hasKey("hyOrderNew")){
            redisUtil.del("hyOrderNew");
        }
        redisUtil.set("hyOrderNew",hyOrderNew,60*60);
        for (HyOrderSendAddress item : sendAddressList) {
            item.setOrderId(hyOrderNew.getId());
            item.setCustomerId(customerId);
            item.setId("");
        }
        hyOrderSendAddressService.saveBatch(sendAddressList);

        for (HyOrderReceiveAddress item : receiveAddressList) {
            item.setOrderId(hyOrderNew.getId());
            item.setCustomerId(customerId);
            item.setId("");
        }
        hyOrderReceiveAddressService.saveBatch(receiveAddressList);

        //发布公开货源推送消息给司机
        if("2".equals(hyOrder.getOrderType())){
            GenMqUtil.sendMsg(EnumGenHandler.WEBSOCKET_XXTS_HANDLER, orderNum, "0");
        }

        return Result.OK("添加成功");
    }

    /**
     * 验证运费风控指标
     *
     * @return
     */
    public Result<?> checkingFreight(HyOrder hyOrder) {

        //运输里程
        double m = LngLonUtil.GetDistance(hyOrder.getSendLatitude(), hyOrder.getSendLongitude(),
                hyOrder.getReceiveLatitude(), hyOrder.getReceiveLongitude());
        double km = Math.round((m / 100d) / 10d);
        HyCustomerConfig customerConfig = customerConfigService.getByCId(hyOrder.getCustomerId());
        BigDecimal yujiYunfeiDanjia = new BigDecimal(0);
        if (customerConfig != null) {
            if (km < 100) {
                Integer xiaoHundred = customerConfig.getXiaoHundred();
                yujiYunfeiDanjia = BigDecimal.valueOf(xiaoHundred);

            } else if (km > 100 && km < 1000) {
                Integer daHundred = customerConfig.getDaHundred();
                yujiYunfeiDanjia = BigDecimal.valueOf(daHundred);
            } else {
                Integer daHundred = customerConfig.getDaHundred();
                yujiYunfeiDanjia = BigDecimal.valueOf(daHundred);
            }
            if(yujiYunfeiDanjia.compareTo(BigDecimal.ZERO)==1){
                if ("1".equals(hyOrder.getPayType())) {

                    if (hyOrder.getShippingUnitPrice().compareTo(yujiYunfeiDanjia) == 1) {
                        return Result.error("风控提示：运费单价超出预期!");
                    }
                }
                if ("2".equals(hyOrder.getPayType())) {
                    if (hyOrder.getCarrierUnitFee().compareTo(yujiYunfeiDanjia) == 1) {
                        return Result.error("风控提示：运费单价超出预期!");
                    }
                }
                if ("3".equals(hyOrder.getPayType())) {
                    if (hyOrder.getPreUnitFee().compareTo(yujiYunfeiDanjia) == 1) {
                        return Result.error("风控提示：运费单价超出预期!");
                    }
                }
            }


        }
        return Result.OK();
    }


    @Override
    @Transactional
    public Result<?> editOrder(HyOrderDTO hyOrder) {
        String id = hyOrder.getId();
        if (StringUtils.isEmpty(id)) {
            return Result.error("id不能为空");
        }
        HyOrder oldorder = this.getById(id);
        if (oldorder == null) {
            return Result.error("货源信息不存在");
        }
//        if(!"0".equals(oldorder.getOrderStatus())){
////            return Result.error("货源信息已发布,不能修改");
//        }

        HyCustomer customer = null;
        if (userUtil.isSys()) {
            String customerId = oldorder.getCustomerId();
            if (StringUtils.isEmpty(customerId)) {
                return Result.error("货主信息不存在");
            }
            customer = userUtil.getCustomerById(customerId);
        } else {
            customer = userUtil.getCustomer();
        }
        if (customer == null) {
            return Result.error("货主信息不存在");
        }
        String customerId = hyOrder.getCustomerId();



        if ("3".equals(hyOrder.getOrderMode())) {

            if (StringUtils.isEmpty(customerId)) {
                return Result.error("货主不能为空");
            }
            String agentId = hyOrder.getAgentId();
            if (StringUtils.isEmpty(agentId)) {
                return Result.error("经纪人不能为空");
            }

            if (!StringUtils.equals(agentId, customer.getId())
                    && !StringUtils.equals(customerId, customer.getId())
            ) {
                return Result.error("货源信息错误!");
            }


            //货主发布差价货源
            if (StringUtils.equals(customerId, customer.getId())) {
                BigDecimal agentPrice = hyOrder.getAgentPrice();
                if (agentPrice == null) {
                    return Result.error("经纪人运费不能为空");
                }
            }
            //经纪人代发差价货源
            if (StringUtils.equals(agentId, customer.getId())) {
                BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
                if (shippingUnitPrice == null) {
                    return Result.error("司机运费不能为空");
                }
            }
        } else {
            customerId = customer.getId();
            hyOrder.setAgentId("");
            hyOrder.setAgentPrice(BigDecimal.ZERO);
            if (!StringUtils.equals(hyOrder.getCustomerId(), customer.getId())) {
                return Result.error("货源信息错误!");
            }
        }

        HyCustomerCompany customerCompany = userUtil.getCustomerCompany(customerId);
        BigDecimal costServicePercent = customerCompany.getCostServicePercent();
        if (costServicePercent == null) {
            return Result.error("公司服务信息错误");
        }

        //账期计算
        String shippingType = hyOrder.getShippingType();
        HyStatusCheckUtil.checkShippingType(shippingType);

        //验证油气费
        String izUsedGas = hyOrder.getIzUsedGas();
        if ("0".equals(izUsedGas)) {
            hyOrder.setGasRechargeAmount(BigDecimal.ZERO);
        } else {
            BigDecimal gasRechargeAmount = hyOrder.getGasRechargeAmount();
            if (gasRechargeAmount == null) {
                return Result.error("油气充值金额不正确");
            }
//            HyCompanyConfig companyConfig = hyCompanyConfigService.getByCompanyId(customerCompany.getCompanyId());
//            if(companyConfig == null){
//                return Result.error("未找到公司配置信息!");
//            }
//            if(!companyConfig.getIzGasUsed()){
//                return Result.error("签约公司不支持油气!");
//            }
            if ("1".equals(izUsedGas)) {
                //万金油
                HyConfig gasConfig = HyConfigUtils.getConfig();
                if (gasConfig == null) {
                    return Result.error("未找到万金油配置信息!");
                }
                if (!gasConfig.getGasIzUse()) {
                    return Result.error("万金油功能已关闭!");
                }
            }
            if ("3".equals(izUsedGas)) {
                //油气平台
                HyConfig gasConfig = HyConfigUtils.getConfig();
                if (gasConfig == null) {
                    return Result.error("未找到油气平台配置信息!");
                }
                if (!gasConfig.getHgGasIzUse()) {
                    return Result.error("油气平台功能已关闭!");
                }
            }
        }

        String payType = hyOrder.getPayType();
        HyStatusCheckUtil.checkPayType(payType);
        if ("2".equals(payType)) {
            String carrierId = hyOrder.getCarrierId();
            if (StringUtils.isEmpty(carrierId)) {
                return Result.error("代收人不能为空!");
            }
            String carrierFeeType = hyOrder.getCarrierFeeType();
            if ("1".equals(carrierFeeType)) {
                if (!"1".equals(hyOrder.getShippingType())) {
                    return Result.error("代收人运费计算方式必须是按单价");
                }
                BigDecimal carrierUnitFee = hyOrder.getCarrierUnitFee();
                if (carrierUnitFee == null || carrierUnitFee.compareTo(BigDecimal.ZERO) <= 0) {
                    return Result.error("代收人运费单价不能为0");
                }
                if (carrierUnitFee.compareTo(hyOrder.getShippingUnitPrice()) > 0) {
                    return Result.error("代收人运费单价不能大于运费单价");
                }
            }else if("2".equals(carrierFeeType)) {
                BigDecimal carrierUnitFee = hyOrder.getCarrierUnitFee();
                if (carrierUnitFee == null || carrierUnitFee.compareTo(BigDecimal.ZERO) <= 0) {
                    return Result.error("代收人运费不能为0");
                }
            } else {
                hyOrder.setCarrierFeeType("0");
                hyOrder.setCarrierUnitFee(BigDecimal.ZERO);
            }
        } else {
            hyOrder.setCarrierFeeType("0");
            hyOrder.setCarrierUnitFee(BigDecimal.ZERO);
        }

        if ("3".equals(payType)) {
            String preType = hyOrder.getPreType();
            if (StringUtils.isEmpty(preType)) {
                return Result.error("预付运费计算方式不能为空!");
            }
            if (!"1".equals(preType) && !"2".equals(preType)) {
                return Result.error("预付运费计算方式错误");
            }
            BigDecimal preUnitFee = hyOrder.getPreUnitFee();
            if (preUnitFee == null) {
                return Result.error("预付运费不能为空");
            }
            if (!ConvertUtil.isMoney(preUnitFee.toString())) {
                return Result.error("预付运费错误");
            }
        }


        //处理收发货
        List<HyOrderSendAddress> sendAddressList = hyOrder.getHyOrderSendAddressList();
        if (sendAddressList == null) {
            return Result.error("未添加发货地址");
        }
        if (sendAddressList.size() == 0) {
            return Result.error("未添加发货地址");
        }
        int sendDestNums = 0;
        HyOrderSendAddress hyOrderSendAddressDest = null;
        for (HyOrderSendAddress item : sendAddressList) {
            if (StringUtils.isEmpty(item.getSendAddress())) {
                return Result.error("发货地址不能为空");
            }
            if (StringUtils.isEmpty(item.getSendContactName())) {
                return Result.error("发货联系人不能为空");
            }
            if (StringUtils.isEmpty(item.getSendContactTel())) {
                return Result.error("发货联系人电话不能为空");
            }
            if (StringUtils.isEmpty(item.getSendAreaCode())) {
                return Result.error("发货地省市区不能为空");
            }
            BigDecimal lat = item.getSendLatitude();
            BigDecimal lng = item.getSendLongitude();
            if (lat == null || lng == null) {
                return Result.error("发货地址经纬度不能为空");
            }
            if (item.isIzDest()) {
                hyOrderSendAddressDest = item;
                sendDestNums++;
            }
        }
        if (sendDestNums == 0) {
            return Result.error("发货地址未添加始发地");
        }
        if (sendDestNums > 1) {
            return Result.error("发货地址不能有多个始发地");
        }

        hyOrder.setAddressSendId(hyOrderSendAddressDest.getAddressSendId());
        hyOrder.setSendDate(hyOrderSendAddressDest.getSendDate());
        hyOrder.setSendAddressName(hyOrderSendAddressDest.getSendAddressName());
        hyOrder.setSendLongitude(hyOrderSendAddressDest.getSendLongitude());
        hyOrder.setSendLatitude(hyOrderSendAddressDest.getSendLatitude());
        hyOrder.setSendAddress(hyOrderSendAddressDest.getSendAddress());
        hyOrder.setSendAreaCode(hyOrderSendAddressDest.getSendAreaCode().substring(0,6));
        hyOrder.setSendContactName(hyOrderSendAddressDest.getSendContactName());
        hyOrder.setSendContactTel(hyOrderSendAddressDest.getSendContactTel());
        hyOrder.setSendContactCredit(hyOrderSendAddressDest.getSendContactCredit());

        //收货地址
        List<HyOrderReceiveAddress> receiveAddressList = hyOrder.getHyOrderReceiveAddressList();
        if (receiveAddressList == null) {
            return Result.error("未添加收货地址");
        }
        if (receiveAddressList.size() == 0) {
            return Result.error("未添加收货地址");
        }
        int receiveDestNums = 0;
        HyOrderReceiveAddress hyOrderReceiveAddressDest = null;
        for (HyOrderReceiveAddress item : receiveAddressList) {
            if (StringUtils.isEmpty(item.getReceiveAddress())) {
                return Result.error("收货地址不能为空");
            }
            if (StringUtils.isEmpty(item.getReceiveContactName())) {
                return Result.error("收货联系人不能为空");
            }
            if (StringUtils.isEmpty(item.getReceiveContactTel())) {
                return Result.error("收货联系人电话不能为空");
            }
            if (StringUtils.isEmpty(item.getReceiveAreaCode())) {
                return Result.error("收货地省市区不能为空");
            }
            BigDecimal lat = item.getReceiveLatitude();
            BigDecimal lng = item.getReceiveLongitude();
            if (lat == null || lng == null) {
                return Result.error("收货地址经纬度不能为空");
            }
            if (item.isIzDest()) {
                hyOrderReceiveAddressDest = item;
                receiveDestNums++;
            }
        }
        if (receiveDestNums == 0) {
            return Result.error("收货地址未添加目的地");
        }
        if (receiveDestNums > 1) {
            return Result.error("收货地址不能有多个目的地");
        }

        hyOrder.setAddressReceiveId(hyOrderReceiveAddressDest.getAddressReceiveId());
        hyOrder.setReceiveDate(hyOrderReceiveAddressDest.getReceiveDate());
        hyOrder.setReceiveAddressName(hyOrderReceiveAddressDest.getReceiveAddressName());
        hyOrder.setReceiveLongitude(hyOrderReceiveAddressDest.getReceiveLongitude());
        hyOrder.setReceiveLatitude(hyOrderReceiveAddressDest.getReceiveLatitude());
        hyOrder.setReceiveAddress(hyOrderReceiveAddressDest.getReceiveAddress());
        hyOrder.setReceiveAreaCode(hyOrderReceiveAddressDest.getReceiveAreaCode().substring(0,6));
        hyOrder.setReceiveContactName(hyOrderReceiveAddressDest.getReceiveContactName());
        hyOrder.setReceiveContactTel(hyOrderReceiveAddressDest.getReceiveContactTel());
        hyOrder.setReceiveContactCredit(hyOrderReceiveAddressDest.getReceiveContactCredit());

        if (!"2".equals(hyOrder.getPayType())) {
            hyOrder.setCarrierId("");
        }

        if ("1".equals(hyOrder.getOrderType())) {
            hyOrder.setOrderType2("");
        }
        //验证货源单价风控
        Result<?> result = checkingFreight(hyOrder);
        if (result.getCode() == 500) {
            return result;
        }

        //鄂尔多斯市监管判断收发货必须有一个地点在内蒙古范围内
        if (HyCfgUtil.isUsed2("ordos_report")) {
            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(customerCompany.getCompanyId());
            //200是鄂尔多斯市监管平台，写死的
            if (hyCompanyConfig.getParkReportPlatformType().intValue() == 200) {
                if (!hyOrder.getSendAddress().contains("内蒙古") && !hyOrder.getReceiveAddress().contains("内蒙古")) {
                    return Result.error("发货或收货地址必须有一个在内蒙古自治区范围内");
                }
            }

            HyCustomer hyCustomer = this.hyCustomerService.getById(customerId);
            if (!"1".equals(hyCustomer.getTosUploadStatus())) {
                return Result.error("请先上报货主信息到鄂尔多斯市监管平台!");
            }
        }


        HyOrder hyOrderNew = new HyOrder();
        BeanUtils.copyProperties(hyOrder, hyOrderNew);
        this.updateById(hyOrderNew);

        //删除
        hyOrderSendAddressService.deleteByOrderId(hyOrder.getId());
        for (HyOrderSendAddress item : sendAddressList) {
            item.setOrderId(hyOrderNew.getId());
            item.setCustomerId(customerId);
        }
        hyOrderSendAddressService.saveBatch(sendAddressList);

        hyOrderReceiveAddressService.deleteByOrderId(id);
        for (HyOrderReceiveAddress item : receiveAddressList) {
            item.setOrderId(hyOrderNew.getId());
            item.setCustomerId(customerId);
        }
        hyOrderReceiveAddressService.saveBatch(receiveAddressList);

        return Result.OK("编辑成功!");
    }

    /**
     * 导入货源
     *
     * @param listOrders
     */
    @Override
    @Transactional
    public void saveBatchOrder(List<HyOrder> listOrders) {

        if (CollectionUtils.isNotEmpty(listOrders)) {
            //写入货主收发货地址管理
            List<HyCustomerAddressReceive> hyCustomerAddressReceiveList = new ArrayList<>();
            List<HyCustomerAddressSend> hyCustomerAddressSendList = new ArrayList<>();

            log.info("生成货主收发货地址数据, {}", listOrders.size());
            for (HyOrder order : listOrders) {
                HyCustomerAddressReceive customerAddressReceive = OrderTOCustomerAddressReceive(order);
                if (customerAddressReceive != null) {
                    //导入的重复收货地址要过滤掉
                    if (CollUtil.isNotEmpty(hyCustomerAddressReceiveList)
                     && 0 < hyCustomerAddressReceiveList.stream().filter(r->r.getAddress().equals(customerAddressReceive.getAddress())).count()) {
                        //导入地址重复，暂时不存
                        //...
                    } else {
                        hyCustomerAddressReceiveList.add(customerAddressReceive);
                    }
                }
                HyCustomerAddressSend customerAddressSend = OrderTOCustomerAddressSend(order);
                if (customerAddressSend != null) {
                    if (CollUtil.isNotEmpty(hyCustomerAddressSendList)
                    && 0 < hyCustomerAddressSendList.stream().filter(s->s.getAddress().equals(customerAddressSend.getAddress())).count()) {
                        //导入地址重复，暂时不存
                        //TODO 日志标记，后续没问题会删除...
                        log.warn("导入货主发货地址重复, {}", JSONUtil.toJsonStr(customerAddressSend));
                    } else {
                        hyCustomerAddressSendList.add(customerAddressSend);
                    }
                }
            }

            log.info("保存货主收发货地址数据, {} {}", hyCustomerAddressSendList.size(), hyCustomerAddressReceiveList.size());
            if (CollectionUtils.isNotEmpty(hyCustomerAddressReceiveList)) {
                customerAddressReceiveService.saveBatch(hyCustomerAddressReceiveList);
            }
            if (CollectionUtils.isNotEmpty(hyCustomerAddressSendList)) {
                customerAddressSendService.saveBatch(hyCustomerAddressSendList);
            }
            //保存货源
            Map<String, String> customerAddressReceiveMaps = hyCustomerAddressReceiveList.stream().collect(
                    Collectors.toMap(HyCustomerAddressReceive::getAddressName, HyCustomerAddressReceive::getId, (key1, key2) -> key2)
            );

            Map<String, String> customerAddressSendMaps = hyCustomerAddressSendList.stream().collect(
                    Collectors.toMap(HyCustomerAddressSend::getAddressName, HyCustomerAddressSend::getId, (key1, key2) -> key2)
            );

            List<HyOrder> orders = listOrders.stream().map(
                    item -> {
                        item.setAddressSendId(customerAddressSendMaps.get(item.getSendAddressName()));
                        item.setAddressReceiveId(customerAddressReceiveMaps.get(item.getReceiveAddressName()));
                        return item;
                    }
            ).collect(Collectors.toList());

            log.info("保存货源数据, {}", orders.size());
            this.saveBatch(orders);
            //写入货源附属表
            List<HyOrderSendAddress> orderSendAddresList = new ArrayList<>();
            List<HyOrderReceiveAddress> orderReceiveAddresList = new ArrayList<>();
            for (HyOrder order : orders) {
                HyOrderSendAddress orderSendAddress = OrderTOOrderSendAddres(order);
                if (orderSendAddress != null) {
                    orderSendAddresList.add(orderSendAddress);
                }
                HyOrderReceiveAddress orderReceiveAddress = OrderTOOrderReceiveAddres(order);
                if (orderReceiveAddress != null) {
                    orderReceiveAddresList.add(orderReceiveAddress);
                }

            }

            log.info("保存货源收发货地址数据, {}, {}", orderSendAddresList.size(), orderReceiveAddresList.size());
            if (CollectionUtils.isNotEmpty(orderSendAddresList)) {
                hyOrderSendAddressService.saveBatch(orderSendAddresList);
            }
            if (CollectionUtils.isNotEmpty(orderReceiveAddresList)) {
                hyOrderReceiveAddressService.saveBatch(orderReceiveAddresList);
            }
        }

    }


    public static HyCustomerAddressSend OrderTOCustomerAddressSend(HyOrder order) {
        if (order == null) {
            return null;
        }
        HyCustomerAddressSend hyCustomerAddressSend = new HyCustomerAddressSend();
        hyCustomerAddressSend.setCustomerId(order.getCustomerId());
        hyCustomerAddressSend.setAddressName(order.getSendAddressName());
        hyCustomerAddressSend.setLongitude(order.getSendLongitude());
        hyCustomerAddressSend.setLatitude(order.getSendLatitude());
        hyCustomerAddressSend.setAddress(order.getSendAddress());
        hyCustomerAddressSend.setAreaCode(order.getSendAreaCode());
        hyCustomerAddressSend.setContactName(order.getSendContactName());
        hyCustomerAddressSend.setContactTel(order.getSendContactTel());
        return hyCustomerAddressSend;
    }

    public static HyCustomerAddressReceive OrderTOCustomerAddressReceive(HyOrder order) {
        if (order == null) {
            return null;
        }
        HyCustomerAddressReceive hyCustomerAddressReceive = new HyCustomerAddressReceive();
        hyCustomerAddressReceive.setCustomerId(order.getCustomerId());
        hyCustomerAddressReceive.setAddressName(order.getReceiveAddressName());
        hyCustomerAddressReceive.setLongitude(order.getReceiveLongitude());
        hyCustomerAddressReceive.setLatitude(order.getReceiveLatitude());
        hyCustomerAddressReceive.setAddress(order.getReceiveAddress());
        hyCustomerAddressReceive.setAreaCode(order.getReceiveAreaCode());
        hyCustomerAddressReceive.setContactName(order.getReceiveContactName());
        hyCustomerAddressReceive.setContactTel(order.getReceiveContactTel());
        return hyCustomerAddressReceive;
    }

    public static HyOrderReceiveAddress OrderTOOrderReceiveAddres(HyOrder order) {
        if (order == null) {
            return null;
        }
        HyOrderReceiveAddress hyOrderReceiveAddress = new HyOrderReceiveAddress();
        hyOrderReceiveAddress.setOrderId(order.getId());
        hyOrderReceiveAddress.setCustomerId(order.getCustomerId());
        hyOrderReceiveAddress.setIzDest(true);
        hyOrderReceiveAddress.setAddressReceiveId(order.getAddressReceiveId());
        hyOrderReceiveAddress.setReceiveDate(order.getReceiveDate());
        hyOrderReceiveAddress.setReceiveAddressName(order.getReceiveAddressName());
        hyOrderReceiveAddress.setReceiveLongitude(order.getReceiveLongitude());
        hyOrderReceiveAddress.setReceiveLatitude(order.getReceiveLatitude());
        hyOrderReceiveAddress.setReceiveAddress(order.getReceiveAddress());
        hyOrderReceiveAddress.setReceiveAreaCode(order.getReceiveAreaCode());
        hyOrderReceiveAddress.setReceiveContactName(order.getReceiveContactName());
        hyOrderReceiveAddress.setReceiveContactTel(order.getReceiveContactTel());
        return hyOrderReceiveAddress;
    }

    public static HyOrderSendAddress OrderTOOrderSendAddres(HyOrder order) {
        if (order == null) {
            return null;
        }
        HyOrderSendAddress hyOrderSendAddress = new HyOrderSendAddress();
        hyOrderSendAddress.setOrderId(order.getId());
        hyOrderSendAddress.setCustomerId(order.getCustomerId());
        hyOrderSendAddress.setIzDest(true);
        hyOrderSendAddress.setAddressSendId(order.getAddressSendId());
        hyOrderSendAddress.setSendDate(order.getSendDate());
        hyOrderSendAddress.setSendAddressName(order.getSendAddressName());
        hyOrderSendAddress.setSendLongitude(order.getSendLongitude());
        hyOrderSendAddress.setSendLatitude(order.getSendLatitude());
        hyOrderSendAddress.setSendAddress(order.getSendAddress());
        hyOrderSendAddress.setSendAreaCode(order.getSendAreaCode());
        hyOrderSendAddress.setSendContactName(order.getSendContactName());
        hyOrderSendAddress.setSendContactTel(order.getSendContactTel());
        return hyOrderSendAddress;
    }

    @Override
    public HyOrder ImportOrderDTOTOOrder(ImportOrderDTO importOrderDTO, String key) {
        if (importOrderDTO == null) {
            throw new JeecgBootException("数据对象为空");
        }
        HyOrder hyOrder = new HyOrder();


        if (StringUtils.isBlank(importOrderDTO.getCustomerId())) {
            throw new JeecgBootException("第" + key + "行 货主信息不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getDescriptionOfGoods())) {
            throw new JeecgBootException("第" + key + "行 货物名称不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getCargoTypeClassificationCode())) {
            throw new JeecgBootException("第" + key + "行 货物分类不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getShippingUnitPrice())) {
            throw new JeecgBootException("第" + key + "行 运费含税单价不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getPayType())) {
            throw new JeecgBootException("第" + key + "行 运费支付方式不能为空");
        }

        if ("2".equals(importOrderDTO.getPayType()) &&
                StringUtils.isBlank(importOrderDTO.getCarrierId())
        ) {
            throw new JeecgBootException("第" + key + "行 车队长信息不能为空,请先补充车队长信息");
        }

        if (StringUtils.isBlank(importOrderDTO.getSendDate())) {
            throw new JeecgBootException("第" + key + "行 要求发货时间不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getReceiveDate())) {
            throw new JeecgBootException("第" + key + "行 要求交货时间不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getSendAddressName())) {
            throw new JeecgBootException("第" + key + "行 发货地址名称不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getSendAddress())) {
            throw new JeecgBootException("第" + key + "行 发货详细地址不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getSendAddress())) {
            throw new JeecgBootException("第" + key + "行 发货区域代码不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getSendContactName())) {
            throw new JeecgBootException("第" + key + "行 发货联系人不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getSendContactTel())) {
            throw new JeecgBootException("第" + key + "行 发货联系人电话不能为空");
        }

        if (StringUtils.isBlank(importOrderDTO.getReceiveAddressName())) {
            throw new JeecgBootException("第" + key + "行 收货地址名称不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getReceiveAddress())) {
            throw new JeecgBootException("第" + key + "行 收货详细地址不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getReceiveAreaCode())) {
            throw new JeecgBootException("第" + key + "行 收货区域代码不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getReceiveContactName())) {
            throw new JeecgBootException("第" + key + "行 收货联系人不能为空");
        }
        if (StringUtils.isBlank(importOrderDTO.getReceiveContactTel())) {
            throw new JeecgBootException("第" + key + "行 收货联系人电话不能为空");
        }

        if (StringUtils.isBlank(importOrderDTO.getCreateTime())) {
            throw new JeecgBootException("第" + key + "行 创建时间不能为空");
        }
        Date createTime = DateUtils.stringToDateTime(importOrderDTO.getCreateTime());
        if (createTime == null) {
            throw new JeecgBootException("第" + key + "行 创建时间不正确,应为日期时间文本格式");
        }
        hyOrder.setCreateTime(createTime);

        //如果有原始货源号，就用原始的单号
        if (StrUtil.isNotEmpty(importOrderDTO.getOrgOrderNumber())) {
            hyOrder.setOrderNum(importOrderDTO.getOrgOrderNumber());
        } else {
            hyOrder.setOrderNum(codeUtil.createOrderNum(createTime));
        }

        hyOrder.setCustomerId(importOrderDTO.getCustomerId());
        hyOrder.setDescriptionOfGoods(importOrderDTO.getDescriptionOfGoods());
        hyOrder.setCargoTypeClassificationCode(importOrderDTO.getCargoTypeClassificationCode());
        hyOrder.setShippingUnitPrice(new BigDecimal(importOrderDTO.getShippingUnitPrice()));
        hyOrder.setPayType(importOrderDTO.getPayType());
        hyOrder.setCarrierId(importOrderDTO.getCarrierId());
        hyOrder.setSendDate(
                DateUtils.stringToDateTime(importOrderDTO.getSendDate())
        );

        hyOrder.setReceiveDate(
                DateUtils.stringToDateTime(importOrderDTO.getReceiveDate())
        );

        hyOrder.setSendAddressName(importOrderDTO.getSendAddressName());
//        hyOrder.setSendLongitude(importOrderDTO.getSendLongitude());
//        hyOrder.setSendLatitude(importOrderDTO.getSendLatitude());
        hyOrder.setSendAddress(importOrderDTO.getSendAddress());
        hyOrder.setSendAreaCode(importOrderDTO.getSendAreaCode());
        hyOrder.setSendContactName(importOrderDTO.getSendContactName());
        hyOrder.setSendContactTel(importOrderDTO.getSendContactTel());
        hyOrder.setReceiveAddressName(importOrderDTO.getReceiveAddressName());
//        hyOrder.setReceiveLongitude(importOrderDTO.getReceiveLongitude());
//        hyOrder.setReceiveLatitude(importOrderDTO.getReceiveLatitude());
        hyOrder.setReceiveAddress(importOrderDTO.getReceiveAddress());
        hyOrder.setReceiveAreaCode(importOrderDTO.getReceiveAreaCode());
        hyOrder.setReceiveContactName(importOrderDTO.getReceiveContactName());
        hyOrder.setReceiveContactTel(importOrderDTO.getReceiveContactTel());
        hyOrder.setDtPublish(createTime);

        hyOrder.setOrderType("1");
        hyOrder.setBusinessTypeCode("1002996");
        hyOrder.setGoodsUnit("1");
        hyOrder.setLossGoodsUnitPrice(BigDecimal.ZERO);
        hyOrder.setLossProportion(BigDecimal.ZERO);
        hyOrder.setShippingType("1");
        hyOrder.setOrderMode("1");
        //老系统中的原始货源可设置为已完结的货源
        if (StrUtil.isNotEmpty(importOrderDTO.getOrgOrderStatus()) && importOrderDTO.getOrgOrderStatus().equals("已完结")) {
            hyOrder.setOrderStatus("8");
            hyOrder.setDtFinish(new Date());
        } else {
            hyOrder.setOrderStatus("2");
        }

        hyOrder.setOrderImportFlag("1");
        return hyOrder;
    }

    @Override
    public BigDecimal getShippingFinishWeightById(String id) {
        return baseMapper.getShippingFinishWeightById(id);
    }

    @Override
    public int selectOrderZhangQi(String accountingPeriod,String customerId) {
        return baseMapper.selectOrderZhangQi(accountingPeriod,customerId);
    }

    @Override
    @Transactional
    public Result zybOrderFinish(HyOrder hyOrder) {

        String customerId = hyOrder.getCustomerId();
        if (StringUtils.isEmpty(customerId)) {
            return Result.error("货主信息不存在");
        }

        try {
            hyOrder.setOrderStatus("8");
            hyOrder.setDtFinish(new Date());//货源完结日期
            this.updateById(hyOrder);

            List<HyShippingNote> hyShippingNoteList = this.hyShippingNoteService.list(new LambdaQueryWrapper<HyShippingNote>()
                    .eq(HyShippingNote::getOrderId, hyOrder.getId()));

            //遍历运单、终止围栏
            //取消围栏异常时，回滚货源以及运单所有更新请求
            cancelZybShipping(hyOrder.getId(), hyShippingNoteList);

        } catch (Exception e) {
            log.error("智运宝运单完结异常, {}", JSONUtil.toJsonStr(hyOrder));
            e.printStackTrace();
            throw new RuntimeException("货源完结，取消电子围栏异常");
        }

        return Result.OK("操作成功");
    }


    //取消围栏异常时，回滚货源以及运单所有更新请求
    private void cancelZybShipping(String orderId, List<HyShippingNote> shippingNoteList) throws Exception {

        //先对运单中的智运宝设备号进行去重，有可能一个设备对应多个运单
        List<String> vehicleDeviceList = shippingNoteList.stream().filter(
                CommonUtils.distinctByKey(p -> p.getVehicleDevice())).map(HyShippingNote::getVehicleDevice).collect(Collectors.toList());

        log.info("完结货源删除智运宝与货源绑定关系{} {}", orderId, JSONUtil.toJsonStr(vehicleDeviceList));
        for (String device : vehicleDeviceList) {
            Result r = this.zybService.removeDevice(device, orderId);
            log.info("货源完结，删除智运宝与货源绑定关系, {}, {} ,{}", orderId, device, JSONUtil.toJsonStr(r));
        }

        for (HyShippingNote hyShippingNote : shippingNoteList) {
            //如果补全信息后触发货源完结时，运单状态不是已签收，打上标记需要手工处理
            if (!hyShippingNote.getShippingStatus().equals(ShippingStatus.已签收.getValue())) {
                log.info("货源{}补全信息后触发货源完结，{}运单状态不是已签收。", orderId, hyShippingNote.getShippingNoteNumber());
                this.hyShippingNoteService.update(new LambdaUpdateWrapper<HyShippingNote>()
                        .eq(HyShippingNote::getId, hyShippingNote.getId())
                        .set(HyShippingNote::getRemark, "当前货源已完结"));
            }
        }

        return;
    }

//    //取消围栏异常时，回滚货源以及运单所有更新请求
//    private void cancelZybShipping(String orderId, List<HyShippingNote> shippingNoteList) throws Exception {
//
//        //先对运单中的智运宝设备号进行去重，有可能一个设备对应多个运单
//        List<String> vehicleDeviceList = shippingNoteList.stream().filter(
//                CommonUtils.distinctByKey(p -> p.getVehicleDevice())).map(HyShippingNote::getVehicleDevice).collect(Collectors.toList());
//
//        for (String device : vehicleDeviceList) {
//            //只有当车辆智运宝还在当前货源进行业务时，才会触发终止
//            HyZybStatus hyZybStatus = this.zybService.getById(device);
//            log.info("货源完结，删除智运宝与货源绑定关系, {}, {}", orderId, JSONUtil.toJsonStr(hyZybStatus));
//            if (null != hyZybStatus && hyZybStatus.getOrderId().equals(orderId)) {
//                this.zybService.removeDevice(device);
//            }
//        }
//
//        for (HyShippingNote hyShippingNote : shippingNoteList) {
//            //如果补全信息后触发货源完结时，运单状态不是已签收，打上标记需要手工处理
//            if (!hyShippingNote.getShippingStatus().equals(ShippingStatus.已签收.getValue())) {
//                log.info("货源{}补全信息后触发货源完结，{}运单状态不是已签收。", orderId, hyShippingNote.getShippingNoteNumber());
//                this.hyShippingNoteService.update(new LambdaUpdateWrapper<HyShippingNote>()
//                        .eq(HyShippingNote::getId, hyShippingNote.getId())
//                        .set(HyShippingNote::getRemark, "当前货源已完结"));
//            }
//        }
//
//        return;
//    }


    @Override
    public HyOrderApiDTO getInfoById(String id) {
        return baseMapper.getInfoById(id);
    }
    @Override
    public IPage<HyOrderVO> getPageListByCaptaionId(Page<HyOrderVO> page, QueryWrapper<HyOrderVO> queryWrapper) {
        IPage<HyOrderVO> pageList = baseMapper.getPageListByCaptaionId(page, queryWrapper);
        return pageList;
    }
}
